package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chixing.entity.*;
import com.chixing.VO.MovieDetailVO;
import com.chixing.mapper.*;
import com.chixing.service.ICinemaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p >
 *
 * @author liwenjing
 * @since 2025-10-07
 */
@Service
public class CinemaServiceImpl extends ServiceImpl<CinemaMapper, Cinema> implements ICinemaService {
    @Autowired
    private CinemaMapper cinemaMapper;
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private MovieDetailMapper movieDetailMapper;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private HallMapper hallMapper;
    @Override
    public Result getByPage(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        Page<Cinema> page = new Page<>(pageNum,5);
        page = cinemaMapper.selectPage(page,null);
        if(page.getTotal()> 0)
            return Result.getSuccess(page);
        return Result.getFail(null);
    }

    @Override
    public Result getCinemaDetail(Integer cinemaId) {
        // 1. 校验影院ID
        if (cinemaId == null) {
            return Result.getFail("影院ID不能为空");
        }

        // 2. 查询影院基本信息
        Cinema cinema = cinemaMapper.selectById(cinemaId);
        if (cinema == null) {
            return Result.getFail("未找到该影院");
        }

        // 3. 封装影院信息到VO
        MovieDetailVO resultVO = new MovieDetailVO();
        resultVO.setCinemaName(cinema.getCinemaName());
        resultVO.setCinemaAddress(cinema.getCinemaAddress());
        resultVO.setPhone(cinema.getPhone());
        resultVO.setCinemaImage(cinema.getCinemaImage());

        // 4. 查询该影院正在放映的电影（状态为1）
        QueryWrapper<MovieDetail> movieQuery = new QueryWrapper<>();
        // 假设通过schedule关联影院和电影，先查该影院的场次对应的movie_id
        QueryWrapper<Schedule> scheduleQuery = new QueryWrapper<>();
        scheduleQuery.eq("cinema_id", cinemaId);
        List<Schedule> schedules = scheduleMapper.selectList(scheduleQuery);
        if (schedules.isEmpty()) {
            resultVO.setMovieList(new ArrayList<>());
            return Result.getSuccess(resultVO);
        }

        // 提取不重复的movie_id
        List<Integer> movieIds = schedules.stream()
                .map(Schedule::getMovieId)
                .distinct()
                .collect(Collectors.toList());

        // 查询这些电影中状态为1（正在放映）的详情
        movieQuery.in("movie_id", movieIds)
                .eq("statues", 1); // 电影状态为1
        List<MovieDetail> movies = movieDetailMapper.selectList(movieQuery);

        // 5. 封装电影及场次信息
        List<MovieDetailVO.MovieInfo> movieInfoList = new ArrayList<>();
        for (MovieDetail movieDetail : movies) {
            // 从 movie 表查出图片等基础信息
            Movie movieBase = movieMapper.selectById(movieDetail.getMovieId());

            MovieDetailVO.MovieInfo movieInfo = new MovieDetailVO.MovieInfo();
            movieInfo.setMovieId(movieDetail.getMovieId());
            movieInfo.setMovieName(movieDetail.getMovieName());
            movieInfo.setScore(movieDetail.getScore());
            movieInfo.setDurationMinutes(movieDetail.getDurationMinutes());
            movieInfo.setMovieType(movieDetail.getMovieType());
            movieInfo.setActors(movieDetail.getActors());
            movieInfo.setMovieImage(movieBase != null ? movieBase.getMovieImage() : null);


            // 6. 查询该电影在当前影院的场次
            QueryWrapper<Schedule> movieScheduleQuery = new QueryWrapper<>();
            movieScheduleQuery.eq("cinema_id", cinemaId)
                    .eq("movie_id", movieDetail.getMovieId());
            List<Schedule> movieSchedules = scheduleMapper.selectList(movieScheduleQuery);

            // 7. 封装场次信息（转换时间格式、关联影厅）
            List<MovieDetailVO.ScheduleInfo> scheduleInfoList = new ArrayList<>();
            for (Schedule schedule : movieSchedules) {
                MovieDetailVO.ScheduleInfo scheduleInfo = new MovieDetailVO.ScheduleInfo();
                // 转换时间（LocalDateTime -> LocalTime）
                scheduleInfo.setScheduleId(schedule.getScheduleId());
                scheduleInfo.setStartTime(schedule.getStartTime().toLocalTime());
                scheduleInfo.setPrice(schedule.getBasePrice());

                // 查询影厅名称
                Hall hall = hallMapper.selectById(schedule.getHallId()); // 假设Schedule有hall_id字段
                if (hall != null) {
                    scheduleInfo.setHallName(hall.getHallNumber());
                }

                scheduleInfoList.add(scheduleInfo);
            }

            movieInfo.setScheduleList(scheduleInfoList);
            movieInfoList.add(movieInfo);
        }

        resultVO.setMovieList(movieInfoList);
        return Result.getSuccess(resultVO);
    }


}
